<template>
	<div class="feed-container">
		<nav-bar title="发布通告" :custom-back="true" @on-back="handleBack" />
		<!-- 标题输入 -->
		<van-cell-group class="section" style="margin-top: 44px;">
			<van-field v-model="title" placeholder="标题" maxlength="50" class="input-title" />
		</van-cell-group>

		<!-- 接收人 -->
		<van-cell-group class="section">
			<div class="flex-between">
				<span class="label">接收人</span>
				<div class="crew">
					<template v-for="(item, index) in recipient.list">
						<span :key="index" class="tag-item">
							<span class="tag-text">{{ item.label }}</span>
							<van-icon name="cross" @click="delRecipient($event, { item, index })" />
						</span>
					</template>
				</div>
				<van-button icon="plus" size="small" class="add-btn" @click="showRecipientPopup" />
			</div>
		</van-cell-group>

		<!-- 内容输入 -->
		<van-cell-group class="section">
			<van-field v-model="desc" type="textarea" maxlength="200" placeholder="输入内容" :autosize="{ minHeight: 100 }"
				show-word-limit />
		</van-cell-group>

		<!-- 需审核开关 -->
		<van-cell-group class="section">
			<van-cell title="需审核" size="large">
				<template #right-icon>
					<van-switch v-model="isNeedApprove" active-color="#3B6DF8" @change="switchRecall" />
				</template>
			</van-cell>
		</van-cell-group>

		<!-- 审批人(条件渲染) -->
		<van-cell-group v-if="isNeedApprove" class="section">
			<div class="flex-between">
				<span class="label">审批人</span>
				<div class="crew">
					<template v-for="(item, index) in approver.list">
						<span :key="index" class="tag-item">
							<span class="tag-text">{{ item.label }}</span>
							<van-icon name="cross" @click="delApprover($event, { item, index })" />
						</span>
					</template>
				</div>
				<van-button icon="plus" size="small" class="add-btn" @click="showApproverPopup" />
			</div>
		</van-cell-group>

		<!-- 需签收开关 -->
		<van-cell-group class="section">
			<van-cell title="需签收" size="large">
				<template #right-icon>
					<van-switch v-model="isNeedSign" active-color="#3B6DF8" @change="switchNeedSign" />
				</template>
			</van-cell>
		</van-cell-group>

		<!-- 附件上传 -->
		<van-cell-group class="section">
			<van-cell title="添加附件" is-link @click="chooseFile" />
			<div v-if="picArr.length" class="file-list">
				<div v-for="(item, index) in picArr" :key="index" class="file-item">
					<span class="file-name">{{ item.fileName }}</span>
					<van-icon name="cross" @click="delFile(index)" />
				</div>
			</div>
		</van-cell-group>

		<!-- 提交按钮 -->
		<van-button type="primary" block class="submit-btn" @click="submitClick">发布</van-button>

		<!-- 选择接收人弹窗 -->
		<van-popup v-model="showRecipientTree" position="bottom" :style="{ height: '50%' }">
			<tree ref="treeRecipient" :dataTree="dataTree" :is-open-all="true" @select="handleRecipientClick" />
		</van-popup>

		<!-- 选择审批人弹窗 -->
		<van-popup v-model="showApproverTree" position="bottom" :style="{ height: '50%' }">
			<tree ref="treeApprover" :dataTree="dataTree" :is-open-all="true" :is-choice="true"
				@select="handleApproverClick" />
		</van-popup>
	</div>
</template>



<script>
	import NavBar from '@/components/NavBar'
	import {
		saveNotice,
		listNotice,
		getNoticeDetail,
		getDeptUserTree,
		doUploadBatchFile
	} from "@/api/annunciateAdd.js"
	import tree from '@/components/tree/index';
	import {
		Toast,
		Dialog
	} from 'vant'

	export default {
		name: 'NoticeForm',

		components: {
			tree,
			NavBar
		},

		data() {
			return {
				title: '',
				desc: '',
				picArr: [],
				recipient: [],
				approver: [],
				isNeedApprove: true,
				isNeedSign: true,
				showRecipientTree: false,
				showApproverTree: false,
				dataTree: [],
				detailId: 0,
				loading: false,
				user: []
			}
		},

		created() {
			// 获取路由参数
			this.user = JSON.parse(localStorage.getItem('user'))
			this.detailId = this.$route.query.id || 0
			this.getDeptUserTree()
		},

		methods: {
			handleBack() {
				this.$router.push('/annunciate')
			},
			// 获取部门用户树
			getDeptUserTree() {
				try {

					getDeptUserTree({
							openSessionId: this.user.openSessionId,
						})
						.then(res => {

							if (res.code == 200) {
								this.dataTree = res.data
								if (this.detailId) {
									this.initDetailData()
								}
							}
						})

				} catch (err) {
					Toast.fail('获取部门用户树失败')
				}
			},

			// 初始化详情数据
			async initDetailData() {
				try {
					Toast.loading({
						message: '加载中...',
						forbidClick: true
					})

					getNoticeDetail({
							openSessionId: this.user.openSessionId,
							id: this.detailId
						})
						.then(res => {
							if (res.code == 200) {
								const data = res.data

								// 处理接收人
								data.allRecUserList.forEach(recipient => {
									const dataTree = JSON.parse(JSON.stringify(this.dataTree))
									this.updateRecipientTree(dataTree, recipient)
								})

								// 处理审批人
								data.approveList.forEach(approve => {
									const dataTree = JSON.parse(JSON.stringify(this.dataTree))
									this.updateApproverTree(dataTree, approve)
								})

								// 更新表单数据
								this.title = data.noticeInfo.title
								this.desc = data.noticeInfo.content
								this.isNeedApprove = data.noticeInfo.isNeedApprove === 1
								this.isNeedSign = data.noticeInfo.isNeedSign === 1
								this.picArr = data.noticeFileList
							}
						})
				} catch (err) {
					Toast.fail('获取详情失败')
				} finally {
					Toast.clear()
				}
			},

			// 更新接收人树
			updateRecipientTree(tree, newItem) {
				if (!tree?.length) return

				for (const node of tree) {
					if (node.id === newItem.id) {
						this.$refs.treeRecipient.select(node)
					} else if (node.children?.length) {
						this.updateRecipientTree(node.children, newItem)
					}
				}
			},

			// 更新审批人树
			updateApproverTree(tree, newItem) {
				if (!tree?.length) return

				for (const node of tree) {
					if (node.id === newItem.approveUserId) {
						this.$refs.treeApprover.select(node)
					} else if (node.children?.length) {
						this.updateApproverTree(node.children, newItem)
					}
				}
			},

			// 选择接收人
			handleRecipientClick(list) {
				this.recipient = list.detail
				// this.showRecipientTree = false
			},

			// 选择审批人
			handleApproverClick(list) {
				this.approver = list.detail
				// this.showApproverTree = false
			},

			// 删除接收人
			delRecipient(item, index) {
				this.recipient.list.splice(index, 1)
				this.$refs.treeRecipient.select(item)
			},
			// 删除审批人
			delApprover(item, index) {
				this.approver.list.splice(index, 1)
				this.$refs.treeApprover.select(item)
			},

			showRecipientPopup() {
				this.showRecipientTree = true;
			},

			onRecipientClose() {
				this.showRecipientTree = false;
			},

			showApproverPopup() {
				this.showApproverTree = true;
			},

			onApproverClose() {
				this.showApproverTree = false;
			},

			switchRecall(e) {
				this.isNeedApprove = e.detail.value;
			},

			switchNeedSign(e) {
				this.isNeedSign = e.detail.value;
			},



			// 选择文件
			async chooseFile() {
				try {
					const input = document.createElement('input')
					input.type = 'file'
					input.multiple = true
					input.accept = '*/*'
					input.click()

					input.onchange = async () => {
						const files = Array.from(input.files)
						if (!files.length) return

						Toast.loading({
							message: '上传中...',
							forbidClick: true
						})

						const formData = new FormData()
						files.forEach(file => {
							formData.append('file', file)
						})
						// formData.append('openSessionId', this.user.openSessionId)

						doUploadBatchFile(formData)
							.then(res => {
								if (res.code === 200 && res.data[0]) {
									this.picArr = [...this.picArr, ...res.data.data]
								} else {
									Toast.fail(res.message)
								}
							})

					}
				} catch (err) {
					Toast.fail('上传文件失败')
				} finally {
					Toast.clear()
				}
			},

			// 删除文件
			delFile(index) {
				this.picArr.splice(index, 1)
			},

			// 提交表单
			async submitClick() {
				// 表单验证
				if (!this.title) {
					return Toast('标题不能为空')
				}
				if (!this.recipient.list.length) {
					return Toast('至少选择一位接收人')
				}
				if (!this.desc) {
					return Toast('内容不能为空')
				}
				if (this.isNeedApprove && !this.approver.list.length) {
					return Toast('请选择一位审批人')
				}

				try {
					Toast.loading({
						message: '提交中...',
						forbidClick: true
					})

					// 构建参数
					const params = {
						title: this.title,
						content: this.desc,
						approveUserId: this.isNeedApprove ? this.approver.list[0].id : '',
						recUserIds: this.recipient.list.map(item => item.id).join(','),
						isNeedApprove: this.isNeedApprove ? 1 : 0,
						isNeedSign: this.isNeedSign ? 1 : 0,
						fileInfo: this.picArr.length ? JSON.stringify(this.picArr) : '',
						openSessionId :this.user.openSessionId
					}

					if (this.detailId) {
						params.id = this.detailId
					}

					// 发送请求
					const url = this.detailId ? 'updateNotice' : 'saveNotice'

					saveNotice(url, params)
						.then(res => {
							if (res.code === 200) {
								Toast.success('提交成功')

								// 更新上一页数据
								if (!this.detailId) {
									this.$emit('update:curId', '2')
								} else {
									this.$emit('update:detailId', res.data)
								}

								// 返回上一页
								setTimeout(() => {
									this.$router.back()
								}, 1000)
							} else {
								Toast.fail(res.message)
							}
						})

				} catch (err) {
					Toast.fail('提交失败')
				} finally {
					Toast.clear()
				}
			}
		}
	}
</script>
<style lang="scss" scoped>
	.feed-container {
		padding: 10px 20px 20px;
		background-color: #f5f5f5;
		min-height: 100vh;
		text-align: left;

		.section {
			margin: 10px 5px;
			padding: 10px;
			background: white;
			border-radius: 5px;
			border: 1px solid #ddd;
		}

		.flex-between {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

		.label {
			font-size: 16px;
			font-weight: bold;
			min-width: 80px;
		}

		.crew {
			flex: 1;
			margin: 0 10px;
			overflow: hidden;

			.tag-item {
				display: inline-flex;
				align-items: center;
				margin: 2px 5px;
				color: #5e82e5;

				.van-icon {
					margin-left: 5px;
					color: #bbc8ee;
				}
			}
		}

		.file-list {
			margin-top: 10px;
			padding-top: 10px;
			border-top: 1px solid #ddd;

			.file-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 5px 0;

				.file-name {
					flex: 1;
					color: #5e82e5;
					// @include text-ellipsis;
				}
			}
		}

		.submit-btn {
			margin: 20px auto;
			width: 90%;
		}
	}

	// 文本省略
	@mixin text-ellipsis {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	// 覆盖 Vant 样式
	:deep(.van-field__word-limit) {
		margin: 10px 0;
	}
</style>